import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:orginone/components/Tip/ToastUtils.dart';
import 'package:orginone/components/XText/XText.dart';
import 'package:orginone/dart/base/storages/storage.dart';
import 'package:permission_handler/permission_handler.dart';

class PermissionInfo {
  final String title;
  final String desc;
  PermissionInfo(this.title, this.desc);
}

class PermissionUtil {
  static final Map<Permission, PermissionInfo> permissionNameMap = {
    Permission.photos:
        PermissionInfo("相册", "我们需要访问您的相册，以便您可以将照片、图片、视频等下载保存到您的相册中"),
    Permission.camera: PermissionInfo("相机", "请允许我们使用相机以便您可以进行扫码、拍摄和分享照片或视频"),
    Permission.microphone:
        PermissionInfo("录音", "请允许我们访问您的麦克风，以便您可以录制音频或进行语音通话"),
    Permission.storage:
        PermissionInfo("存储", "我们需要访问您的存储，以便您可以将照片、图片、视频等文件下载保存到您的存储中")
  };
  static final Map<Permission, Permission> permissionAndroidMap = {
    Permission.photos: Permission.storage,
    Permission.camera: Permission.camera
  };

  static showPermissionDialog(BuildContext context, Permission permission,
      {Function? callback, bool isShowTip = true}) async {
    if (kIsWeb) {
      await callback?.call();
      return;
    }
    if (Platform.isAndroid) {
      var androidPer = permissionAndroidMap[permission];
      if (androidPer != null) {
        permission = androidPer;
      }
    }
    PermissionInfo? pi = permissionNameMap[permission];
    PermissionStatus status = await permission.status;
    if (status.isDenied) {
      // 未授权，则准备发起一次申请
      var permissionRequestFuture = permission.request().then((value) {
        if (Platform.isAndroid) {
          Navigator.pop(context);
        }
      });

      // 延迟500毫秒的Future
      var delayFuture =
          Future.delayed(const Duration(milliseconds: 500), () => 'delay');

      // 使Future.any等待上述两个Future中的任何一个完成
      var firstCompleted =
          await Future.any([permissionRequestFuture, delayFuture]);

      if (firstCompleted == 'delay') {
        if (Platform.isAndroid) {
          // 如果是延迟Future完成了，表示500毫秒内没有获得权限响应，显示对话框
          _showPermissionDialog(context, '${pi?.desc}');
        }
      } else {
        status = firstCompleted as PermissionStatus;

        bool isShowDialog =
            Storage.getBool("permission_${permission.value}", def: true);
        if (status.isGranted || status.isLimited) {
          await callback?.call();
        } else if (isShowDialog) {
          Storage.setBool("permission_${permission.value}", false);
          String title = '您需要授予${pi?.title}权限';
          String content = '"请转到您的手机设置打开相应${pi?.title}的权限"';

          showCupertinoDialog(
            context: context,
            builder: (context) {
              return CupertinoAlertDialog(
                title: Text(title),
                content: Text(content),
                actions: <Widget>[
                  CupertinoDialogAction(
                    child: const Text('取消'),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                  CupertinoDialogAction(
                    child: const Text('前去设置'),
                    onPressed: () {
                      Navigator.pop(context);
                      openAppSettings();
                    },
                  ),
                ],
              );
            },
          );
        } else if (isShowTip) {
          ToastUtils.showMsg(msg: "您需要授予${pi?.title}权限");
        }
      }
    } else if (status.isGranted) {
      await callback?.call();
    }
  }

  /// 顶部展示权限声明详情弹窗
  static void _showPermissionDialog(BuildContext context, String desc) {
    showDialog(
      context: context,
      builder: (context) {
        return Material(
            type: MaterialType.transparency,
            child: WillPopScope(
              child: Stack(
                children: [
                  GestureDetector(
                    onTap: () {
                      Navigator.of(context).pop();
                    },
                    child: Flex(direction: Axis.vertical, children: [
                      Container(
                        width: MediaQuery.of(context).size.width - 40,
                        margin: const EdgeInsets.all(30),
                        padding: const EdgeInsets.all(20),
                        decoration: const BoxDecoration(
                            color: Colors.white,
                            borderRadius:
                                BorderRadius.all(Radius.circular(20))),
                        child: XText.dialogContent(desc, size: 22.sp),
                      )
                    ]),
                  )
                ],
              ),
              onWillPop: () async {
                Navigator.of(context).pop();
                return Future.value(true);
              },
            ));
      },
    );
  }
}
